package com.jshcbd.mvp_kt_demo.base.activity

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.dylanc.viewbinding.base.inflateBindingWithGeneric
import com.gyf.barlibrary.ImmersionBar
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

abstract class BaseSimpleActivity<VB : ViewBinding> : AppCompatActivity() {
    lateinit var binding: VB
    //关于输入键盘
    private var mInputMethodManager: InputMethodManager? = null
    //沉浸式状态栏的管理
    protected var mImmersionBar: ImmersionBar? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //绑定控件
        initVB()
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            //设置沉浸式状态栏
            initImmersionBar()
        }
        //初始化title
        initTitle()
        //view与数据绑定
        initView()
        //初始化数据
        initData()
        //设置监听
        setListener()
    }

    protected abstract fun initTitle()
    protected abstract fun initView()
    protected abstract fun initData()
    private fun initVB() {
        binding = inflateBindingWithGeneric(layoutInflater)
        setContentView(binding.root)
    }

    protected fun setListener() {}

    /**
     * 设置沉浸式状态栏
     */
    protected fun initImmersionBar() {
        //初始化状态栏，当状态栏设置白色造成系统图标不可见（设置字体）
        mImmersionBar = ImmersionBar.with(this).statusBarDarkFont(true).fitsSystemWindows(true)
        mImmersionBar?.init()
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected fun isImmersionBarEnabled(): Boolean{
        return true
    }

    /**
     * 启动Activity
     */
    protected fun startActivity(clazz: Class<*>?) {
        val intent = Intent(this, clazz)
        startActivity(intent)
    }

    override fun finish() {
        super.finish()
        hideSoftKeyBoard()
    }

    override fun onDestroy() {
        super.onDestroy()
        mInputMethodManager = null
        if (mImmersionBar != null) //必须调用该方法，防止内存泄漏
            mImmersionBar!!.destroy()
    }

    /**
     * activity销毁的时候隐藏键盘弹框
     */
    fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (mInputMethodManager == null) {
            mInputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && mInputMethodManager != null) {
            mInputMethodManager!!.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }
}